<template>
    <div id="update-avatar-box">
        <div class="avatar-box">
            <img :src="loginUserStore.getAvatar" alt="头像" class="user-head">
            <div class="box">
                <a-button class="custom-file-btn" @click="triggerFileSelect" type="primary">更换头像</a-button>
                <input type="file" accept="image/*" @change="handleFileChange" class="file-input" ref="fileInput">
            </div>
        </div>

        <div class="update-avatar-box" v-if="imageUrl">
            <div class="cut-wrapper">
                <img ref="imgRef" :src="imageUrl" alt="示例图片" @load="onImageLoaded">
            </div>
            <div class="preview-box">
                <div style="width: 100%;">预览</div>
                <div id="preview" class="preview"></div>
                <div class="button-box">
                    <a-button @click="getCutImg" type="primary">上传</a-button>
                    <a-button @click="cancelUpdateAvatar">取消</a-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
    import Cropper from 'cropperjs'
    import { ref } from 'vue'
    import 'cropperjs/dist/cropper.css' // 确保引入样式
    import { useLoginUserStore } from '@/store/useLoginUserStore'
    import { updateAvatar } from '@/api/user'
    import { debounce } from '@/utils/index.js'
    const loginUserStore = useLoginUserStore()

    // const topAvatarUrl = computed(loginUserStore.loadAvatar)
    const imgRef = ref()
    const imageUrl = ref()
    const fileInput = ref(null)
    let cropper = null

    // 处理文件选择
    const handleFileChange = (e) => {
        const file = e.target.files[0]
        if (file) {
            // 销毁之前的裁剪实例
            if (cropper) {
                cropper.destroy()
            }
            // 将文件转换为可访问的URL
            imageUrl.value = URL.createObjectURL(file)
        }
        e.target.value = null
    }

    const cancelUpdateAvatar = () => {
        imageUrl.value = null
    }

    // 初始化裁剪器
    const initCropper = () => {
        if (imgRef.value && imageUrl.value) {
            cropper = new Cropper(imgRef.value, {
                aspectRatio: 1,
                viewMode: 1, // 限制裁剪区域在图片内
                preview: '#preview',
                crop() {
                    // console.log('裁剪参数:', {
                    //     x: event.detail.x,
                    //     y: event.detail.y,
                    //     width: event.detail.width,
                    //     height: event.detail.height,
                    //     rotate: event.detail.rotate,
                    //     scaleX: event.detail.scaleX,
                    //     scaleY: event.detail.scaleY
                    // });
                },
            });
        }
    };

    // 图片加载完成后初始化裁剪器
    const onImageLoaded = () => {
        initCropper();
    };
    // 触发文件选择
    const triggerFileSelect = () => {
        fileInput.value.click();
    };

    // 获取图片
    const getCutImg = debounce(() => {
        cropper.getCroppedCanvas().toBlob(async (blob) => {
            // console.log('实际MIME类型:', blob.type); 
            const file = new File([blob], 'newAvatar.png', {
                type: 'image/png'  // 显式指定MIME类型
            })
            console.log(file)
            const res = await updateAvatar(file)
            if (res.data.code !== 0) {
                alert(res.data.msg)
            }
            loginUserStore.fetchLoginUser()
            cancelUpdateAvatar()
        }, 'image/png')
    }, 500)

</script>

<style scoped lang="less">
    #update-avatar-box {
        display: flex;
        flex-direction: column;
        // justify-content: center;
        align-items: center;

        .avatar-box {
            display: flex;

            .box {
                display: flex;
                flex-direction: column;
                justify-content: flex-end;

                .custom-file-btn {
                    height: 30px;
                    width: 80px;
                    padding: 0;
                }

                /* 隐藏原生input，但保持可访问性 */
                .file-input {
                    position: absolute;
                    width: 1px;
                    height: 1px;
                    padding: 0;
                    margin: -1px;
                    overflow: hidden;
                    clip: rect(0, 0, 0, 0);
                    border: 0;
                }
            }

            .user-head {


                border-radius: 50%;
                height: 100px;
                width: 100px;
                background-color: aqua;
            }
        }

        .update-avatar-box {
            display: flex;
            // width: 100%;
            margin-top: 30px;
            background-color: #fff;
            border: solid black 1px;
            border-radius: 5px;

            .cut-wrapper {
                width: 150px;
                height: 150px;
                margin-right: 50px;

                /* 确保图像的大小完全适合容器 */
                img {
                    display: block;

                    /* 这个规则很重要，请不要忽略这个 */
                    max-width: 100%;

                }
            }

            .preview-box {
                padding: 8px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                align-items: center;


                .preview {
                    // position: fixed;
                    width: 50px;
                    height: 50px;
                    border: 1px dashed;
                    overflow: hidden;
                    border-radius: 50%;
                }

                .button-box {
                    width: 150px;
                    display: flex;
                    justify-content: space-between;

                    button {
                        height: 30px;

                    }
                }
            }


        }
    }
</style>